<template>
  <el-card class="form-container" shadow="never">
    <!-- 地址商品分配区块 -->
    <div class="address-blocks">
      <div v-for="(addr, index) in orderData.addresses" :key="addr.addressId" class="address-block">
        <el-card shadow="hover">
          <div class="address-header">
            <h3>{{ formatAddress(addr) }}</h3>
            <el-tag type="info">地址{{ index + 1 }}</el-tag>
          </div>

          <!-- 商品分配表格 -->
          <el-table :data="orderData.addressItems[addr.addressId]" border class="mb-20">
            <el-table-column prop="productId" label="商品ID" width="120"></el-table-column>
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column label="分配数量" width="200">
              <template #default="{ row }">
                <el-input-number
                    v-model="row.orderNum"
                    :min="0"
                    @change="updateTotal"
                />
              </template>
            </el-table-column>
            <el-table-column label="单价" width="120">
              <template #default="{ row }">
                ￥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120">
              <template #default="{ row }">
                ￥{{ (row.price * row.orderNum).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>

          <div class="subtotal">
            本地址小计：￥{{ getAddressTotal(addr.addressId) }}
          </div>
        </el-card>
      </div>
    </div>

    <!-- 订单汇总 -->
    <div class="order-summary">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="total-amount">
            订单总金额：<span>￥{{ orderData.totalAmount }}</span>
          </div>
        </el-col>
        <el-col :span="12" class="text-right">

          <el-button
              class="mr-10"
              @click="handleBack"
              plain
              size="large">
            返 回
          </el-button>

          <el-button
              type="primary"
              size="large"
              @click="handleSubmit"
              :loading="submitting">
            提交订单
          </el-button>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>

<script>
import { getCustomer, addAddr } from "@/api/system/addr";
import { addOrder } from "@/api/system/order";
import { listMerInfo } from "@/api/system/merinfo";
import {getInfo} from "@/api/system/info.js";
import useUserStore from "@/store/modules/user.js";
import {addDetail} from "@/api/system/detail.js";
import {getCategoryByType} from "@/api/system/merinfo";

const userStore = useUserStore();

export default {
  data() {
    return {
      customerInfo:{},
      submitting: false,
      products: [],
      orderData: {
        customerId: null,
        addresses: [],
        totalAmount: 0,
        addressItems: {}
      }
    };
  },
  async mounted() {
    this.getCustomerInfo()
    await this.initOrder();
  },
  methods: {

    handleBack() {

      const hasUnsavedData = Object.values(this.orderData.addressItems).some(
          items => items.some(item => item.orderNum > 0)
      )

      if (!hasUnsavedData) {
        this.navigateBack()
        return
      }

      this.$confirm('您有未提交的订单信息，确定要离开吗？', '提示', {
        confirmButtonText: '确定离开',
        cancelButtonText: '继续编辑',
        type: 'warning',
        distinguishCancelAndClose: true,
        closeOnClickModal: false
      }).then(() => {
        this.navigateBack()
      }).catch(action => {
        if (action === 'cancel') {
          this.$message({
            type: 'info',
            message: '继续编辑订单'
          })
        }
      })
    },

    navigateBack() {

      this.$router.push('/order')
      this.$tab.closePage(this.$route)

    },


    getCustomerInfo(){
      getInfo(userStore.id).then(response => {
        this.customerInfo = response.data;
      }
      )
    },

    async initOrder() {
      try {
        const userStore = useUserStore();
        this.orderData.customerId = userStore.id;

        // 1. 获取地址
        const addrRes = await getCustomer(this.orderData.customerId);
        this.orderData.addresses = addrRes.data.map(addr => ({
          ...addr,
          formattedAddress: this.formatAddress(addr)
        }));

        // 2. 获取商品列表
        const merRes = await getCategoryByType('三级目录');
        const baseProducts = merRes.data.map(item => ({
          ...item,
          orderNum: 0
        }));

        // 3. 为每个地址初始化独立商品数据
        this.orderData.addresses.forEach(addr => {
          this.orderData.addressItems[addr.addressId] = JSON.parse(JSON.stringify(baseProducts))
              .map(p => ({
                ...p,
                addressId: addr.addressId
              }));
        });

      } catch (error) {
        this.$message.error('数据加载失败');
        console.error('初始化失败:', error);
      }
    },

    formatAddress(addr) {
      return [addr.state, addr.city, addr.district, addr.streetAddress, addr.storeName]
          .filter(Boolean)
          .join(' ');
    },

    getAddressTotal(addressId) {
      const items = this.orderData.addressItems[addressId] || [];
      return items.reduce((sum, item) =>
              sum + (item.price * (item.orderNum || 0)),
          0
      ).toFixed(2);
    },


    updateTotal() {
      this.orderData.totalAmount = Object.values(this.orderData.addressItems)
          .flat()
          .reduce((sum, item) => sum + (item.price * item.orderNum), 0)
          .toFixed(2);
    },

    async handleSubmit() {
      try {
        this.submitting = true;
        const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');

        // 构建订单详情
        const orderDetails = [];
        this.orderData.addresses.forEach(addr => {
          const items = this.orderData.addressItems[addr.addressId] || [];
              items.filter(item =>  item.orderNum > 0).forEach(item => {
            orderDetails.push({
              orderId: `ORD-${randomNum}`,
              productId: item.productId,
              productSalesQuantity: item.orderNum,
              subtotal: item.price,
              totalAmount: (item.price * item.orderNum).toFixed(2),
              addressId: addr.addressId,
              // customerAddr: addr.formattedAddress,
              discount: parseFloat(0).toFixed(2),
              warehouseCode: item.warehouseCode || 'WH-HEB-001',
              status:4
            });
          });
        });




        const processBase ={
          orderId:`ORD-${randomNum}`,
          orderStatus:'1',
          orderDate: new Date().toISOString().slice(0, 19),
          businessType:this.customerInfo.businessType,
          customerId: userStore.id,
          paymentMethod:'1',
          orderTotal: this.orderData.totalAmount,
          addressId: '1',
          lastModifiedBy:'管理员',
          note:'无',
        };

        if (orderDetails.length === 0) {
          return this.$message.warning('请至少为一个地址分配商品');
        }

        const orderPayload = {
          customerId: this.orderData.customerId,
          orderTotal: this.orderData.totalAmount,
          details: orderDetails
        };

        addOrder(processBase)

        orderDetails.forEach(item => {
          addDetail(item).then(response => {
          });
        })

        console.log(orderPayload);

        // await addOrder(orderPayload);
        this.$message.success('订单创建成功');
        this.$router.push('/order');
      } catch (error) {
        this.$message.error('订单提交失败');
        console.error('提交失败:', error);
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style scoped>
.form-container {
  max-width: 1200px;
  margin: 20px auto;
}

.address-blocks {
  display: grid;
  gap: 20px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.subtotal {
  text-align: right;
  padding: 10px 0;
  color: #666;
  font-size: 14px;
}

.order-summary {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.total-amount span {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.text-right {
  text-align: right;
}

.mb-20 {
  margin-bottom: 20px;
}
</style>
